<template>
  <div>
    <el-card>
      <el-button type="primary" size="default" icon="Plus" @click="addTradeMark">添加品牌</el-button>
      <el-table style="margin: 10px 0;" border :data="trademarkAttr">
        <el-table-column label="序号" width="80px" align="center" type="index">
        </el-table-column>
        <el-table-column label="品牌名称" prop="tmName">
        </el-table-column>
        <el-table-column label="品牌LOGO" prop="logoUrl">
          <template #="{ row, $index }">
            <img :src="row.logoUrl" alt="无" style="width: 100px;height: 100px;">
          </template>
        </el-table-column>
        <el-table-column label="品牌操作">
          <template #="{ row, $index }">
            <el-button type="primary" size="small" icon="Edit" @click="editTradeMark(row)"></el-button>
            <!-- <el-button type="primary" size="small" icon="Delete" @click="deleteTradeMark(row)"></el-button> -->
            <el-popconfirm :title="`您确认删除${row.tmName}吗？`" @confirm="removeTradeMark(row.id)" width="250px" icon="Delete">
              <template #reference>
                <el-button type="primary" size="small" icon="Delete"></el-button>
              </template>
            </el-popconfirm>

          </template>
        </el-table-column>

      </el-table>
      <el-pagination v-model:current-page="pageNo" v-model:page-size="limit" :page-sizes="[3, 5, 10, 20]"
        :background="true" layout="prev, pager, next, jumper,->,sizes,total" :total="total"
        @current-change="getHasTrademark" @size-change="sizeChange" />


    </el-card>
    <el-dialog :title="dialogTitle" v-model="dialogFormVisible" @close="">
      <el-form style="width: 80%;" :model="trademarkParams" :rules="rules" ref="formRef">
        <el-form-item label="品牌名称" label-width="80px" prop="tmName">
          <el-input placeholder="请输入品牌名称" v-model="trademarkParams.tmName"></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" label-width="80px" prop="logoUrl">
          <el-upload class="avatar-uploader" action="/api/admin/product/fileUpload" :headers="uploadHeaders"
            :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="trademarkParams.logoUrl" :src="trademarkParams.logoUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" size="default" @click="cancel">取消</el-button>
        <el-button type="primary" size="default" @click="confirm">确定</el-button>

      </template>

    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, computed, nextTick } from 'vue';
import { reqHasTrademark, reqAddOrUpdateTrademark, reqDeleteTrademark } from '@/api/product/trademark'
import type { Records, TradeMarkResponseData, TradeMark } from '@/api/product/trademark/type'
import useUserStore from '@/store/modules/user';
import { ElMessage, type UploadProps } from 'element-plus'
import { number } from 'echarts';
let userStore = useUserStore();

// 上传文件的请求头配置
const uploadHeaders = computed(() => {
  return {
    token: userStore.token
  };
});

let pageNo = ref<number>(1);
let limit = ref<number>(3);
let total = ref<number>(0);
let trademarkAttr = ref<Records>([]);
let dialogTitle = ref<string>("对话框");
let dialogFormVisible = ref<boolean>(false);

let trademarkParams = reactive<TradeMark>({
  tmName: "",
  logoUrl: ""
});
let formRef = ref();
//上传图片组件->上传图片之前触发的钩子函数
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  //钩子是在图片上传成功之前触发,上传文件之前可以约束文件类型与大小
  //要求:上传文件格式png|jpg|gif 4M
  if (rawFile.type == 'image/png' || rawFile.type == 'image/jpeg' || rawFile.type == 'image/gif') {
    if (rawFile.size / 1024 / 1024 < 4) {
      return true;
    } else {
      ElMessage({
        type: 'error',
        message: '上传文件大小小于4M'
      })
      return false;
    }
  } else {
    ElMessage({
      type: 'error',
      message: "上传文件格式务必PNG|JPG|GIF"
    })
    return false;
  }
}

//图片上传成功钩子
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  //response:即为当前这次上传图片post请求服务器返回的数据
  //收集上传图片的地址,添加一个新的品牌的时候带给服务器
  console.log(response)
  trademarkParams.logoUrl = response.data;
  //图片上传成功,清除掉对应图片校验结果
  formRef.value.clearValidate('logoUrl');

}

const getHasTrademark = async (pager = 1) => {
  pageNo.value = pager
  let result = await reqHasTrademark(pageNo.value, limit.value);
  if (result.data.total) {
    total.value = result.data.total
    trademarkAttr.value = result.data.records
  }
}
onMounted(() => {
  getHasTrademark();
});
const sizeChange = () => {
  getHasTrademark();
}

const addTradeMark = () => {
  dialogTitle.value = "添加品牌"
  dialogFormVisible.value = true

  //清空收集数据
  trademarkParams.id = 0;
  trademarkParams.tmName = '';
  trademarkParams.logoUrl = '';

  //第一种写法:ts的问号语法
  // formRef.value?.clearValidate('tmName');
  // formRef.value?.clearValidate('logoUrl');
  nextTick(() => {
    formRef.value.clearValidate('tmName');
    formRef.value.clearValidate('logoUrl');
  })
}
const editTradeMark = (row: TradeMark) => {
  nextTick(() => {
    formRef.value.clearValidate('tmName');
    formRef.value.clearValidate('logoUrl');
  })
  dialogTitle.value = "修改品牌"
  dialogFormVisible.value = true
  // 将行数据赋值给表单参数对象
  Object.assign(trademarkParams, row)
}
//气泡确认框确定按钮的回调
const removeTradeMark = async (id: number) => {
  //点击确定按钮删除已有品牌请求
  let result = await reqDeleteTrademark(id);
  if (result.code == 200) {
    //删除成功提示信息
    ElMessage({
      type: 'success',
      message: '删除品牌成功'
    });
    //再次获取已有的品牌数据
    getHasTrademark(trademarkAttr.value.length > 1 ? pageNo.value : pageNo.value - 1);
  } else {
    ElMessage({
      type: 'error',
      message: '删除品牌失败'
    })
  }
}

const cancel = () => {
  dialogFormVisible.value = false;
}
const confirm = async () => {
  await formRef.value.validate();
  let result = await reqAddOrUpdateTrademark(trademarkParams);
  if (result.code == 200) {
    dialogFormVisible.value = false;
    ElMessage({
      type: 'success',
      message: trademarkParams.id ? "修改品牌成功" : "添加品牌成功"
    });
    getHasTrademark(trademarkParams.id ? pageNo.value : 1);
  } else {
    //添加品牌失败
    ElMessage({
      type: 'error',
      message: trademarkParams.id ? '修改品牌失败' : '添加品牌失败'
    });
    //关闭对话框
    dialogFormVisible.value = false;
  }
}
const validateTmName = (rule: any, value: any, callback: any) => {
  if (value.trim().length >= 2) {
    callback();
  } else {
    callback(new Error('品牌名称大于等于2位'));
  }
}

//品牌LOGO图片的自定义校验规则方法
const validatorLogoUrl = (rule: any, value: any, callBack: any) => {
  //如果图片上传
  if (value) {
    callBack();
  } else {
    callBack(new Error('LOGO图片务必上传'))
  }
}
const rules = {
  tmName: [
    { required: true, trigger: 'blur', validator: validateTmName }
  ],
  logoUrl: [
    { required: true, validator: validatorLogoUrl }
  ]
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
